package com.hhf.feiojjudgeservice.rabbitmq.consumer;

import com.hhf.feiojcommonservice.constant.RabbitMQConstant;
import com.hhf.feiojjudgeservice.service.JudgeService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author hhf
 * @Date 2024/11/4
 * @Description
 */
@Component
@Slf4j
public class JudgeMessageConsumer {

    /**
     * 重试次数5次
     */
    private static final int MAX_RETRIES = 5;

    /**
     * 间隔时间3s
     */
    private static final long RETRY_INTERVAL = 1000 * 3;


    @Resource
    private JudgeService judgeService;

    @RabbitListener(queues = RabbitMQConstant.QUEUE_NAME, ackMode = "MANUAL")
    public void receiveMessage(Message message, Channel channel) throws IOException, InterruptedException {

        int retryCount = 0;
        boolean success = false;

        //消费失败 & 重试次数 < MAX
        while (!success && retryCount < MAX_RETRIES) {
            retryCount++;
            //具体业务
            String body = new String(message.getBody(), StandardCharsets.UTF_8);
            long questionSubmitId = Long.parseLong(body);
            try {

                //手动异常
                //int i = 1 / 0;

                judgeService.doJudge(questionSubmitId);
                success = true;
            } catch (Exception e) {
                log.error("judgeService 内部调用出错:{}", e.getMessage());
            }
            if (!success) {
                String errorTip = "第" + retryCount + "次消费失败" +
                        ((retryCount < MAX_RETRIES) ? "," + RETRY_INTERVAL + "s后重试" : ",进入死信队列");
                log.error(errorTip);
                Thread.sleep(RETRY_INTERVAL);
            }
        }
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        if (success) {
            channel.basicAck(deliveryTag, false);
            log.info("消费成功");
        } else {
            // 重试多次之后仍失败，进入死信队列
            channel.basicNack(deliveryTag, false, false);
            log.error("消费失败");
        }
    }


    /**
     * 手动(MANUAL)处理消息
     * @param message
     * @param channel
     * @param deliveryTag
     */
//    @SneakyThrows
//    @RabbitListener(queues = {RabbitMQConstant.QUEUE_NAME},ackMode = "MANUAL")
//    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag){
//
//        log.info("receiveMessage message = {}",message);
//
//        long questionSubmitId = Long.parseLong(message);
//
//        try {
//            judgeService.doJudge(questionSubmitId);
//            channel.basicAck(deliveryTag,false);
//        } catch (Exception e) {
//            channel.basicNack(deliveryTag,false,false);
//        }
//
//    }
}
